<template>
  <div class="exchange-page">
    <!-- 顶部导航栏 -->
    <HeaderNav />
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">
          <div class="page-title-icon">💳</div>
          福利卡兑换
        </h1>
        <p class="page-description">输入卡号和密码兑换福利额度，立即到账</p>
      </div>
      
      <!-- 统计卡片区域 -->
      <div class="stats-section">
        <div class="stat-card stat-card-primary">
          <div class="stat-icon">💰</div>
          <div class="stat-content">
            <div class="stat-label">当前余额</div>
            <div class="stat-value">¥{{ formatBalance(userStore.userInfo?.accountBalance) }}</div>
          </div>
        </div>
        <div class="stat-card stat-card-success">
          <div class="stat-icon">🎫</div>
          <div class="stat-content">
            <div class="stat-label">已发放卡片</div>
            <div class="stat-value">{{ myCards.length }}</div>
          </div>
        </div>
        <div class="stat-card stat-card-warning">
          <div class="stat-icon">✅</div>
          <div class="stat-content">
            <div class="stat-label">已兑换记录</div>
            <div class="stat-value">{{ exchangedCards.length }}</div>
          </div>
        </div>
      </div>
      
      <!-- 兑换卡片 -->
      <div class="exchange-card">
        <div class="card-header">
          <h2 class="card-title">
            <span class="card-icon">✨</span>
            兑换额度卡
          </h2>
        </div>
        
        <div class="card-content">
          <el-form ref="exchangeFormRef" :model="exchangeForm" :rules="exchangeRules" label-width="90px">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="卡号" prop="cardNumber" class="form-item-compact">
                  <el-input 
                    v-model="exchangeForm.cardNumber" 
                    placeholder="请输入16位卡号"
                    clearable
                    maxlength="16"
                    size="large"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="密码" prop="cardPassword" class="form-item-compact">
                  <el-input 
                    v-model="exchangeForm.cardPassword" 
                    type="password"
                    placeholder="请输入16位密码"
                    clearable
                    maxlength="16"
                    show-password
                    size="large"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item class="action-buttons">
              <el-button 
                class="exchange-btn" 
                type="primary" 
                size="large"
                @click="handleExchange"
                :loading="exchanging"
              >
                <span class="btn-icon">✨</span>
                立即兑换
              </el-button>
              <el-button 
                class="verify-btn" 
                size="large"
                @click="handleVerify"
                :loading="verifying"
              >
                <span class="btn-icon">🔍</span>
                验证卡密
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <!-- 我的额度卡列表 -->
      <div class="cards-list-card">
        <div class="card-header">
          <h2 class="card-title">
            <span class="card-icon">📜</span>
            我的额度卡
          </h2>
        </div>
        
        <div class="card-content">
          <el-tabs v-model="cardTab" @tab-change="handleCardTabChange">
            <el-tab-pane label="已发放" name="issued">
              <el-empty v-if="myCards.length === 0" description="暂无已发放的额度卡" />
              <el-table :data="myCards" v-loading="cardsLoading" stripe v-else>
                <el-table-column prop="cardNumber" label="卡号" width="200" />
                <el-table-column prop="cardPassword" label="密码" width="200" />
                <el-table-column prop="amount" label="面额" width="100">
                  <template #default="{ row }">
                    <span class="amount-text">¥{{ row.amount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="issueTime" label="发放时间" width="180">
                  <template #default="{ row }">
                    {{ formatDateTime(row.issueTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="expireTime" label="过期时间" width="180">
                  <template #default="{ row }">
                    {{ formatDateTime(row.expireTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            
            <el-tab-pane label="已兑换" name="exchanged">
              <el-empty v-if="exchangedCards.length === 0" description="暂无已兑换的记录" />
              <el-table :data="exchangedCards" v-loading="cardsLoading" stripe v-else>
                <el-table-column prop="cardNumber" label="卡号" width="200" />
                <el-table-column prop="amount" label="面额" width="100">
                  <template #default="{ row }">
                    <span class="amount-text">¥{{ row.amount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="issueTime" label="发放时间" width="180">
                  <template #default="{ row }">
                    {{ formatDateTime(row.issueTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="useTime" label="兑换时间" width="180">
                  <template #default="{ row }">
                    {{ formatDateTime(row.useTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import HeaderNav from '@/components/HeaderNav.vue'
import { useUserStore } from '@/stores/user'
import { exchangeCard, getMyCards, verifyCard } from '@/api/welfareCard'

// 使用userStore
const userStore = useUserStore()

// 额度卡相关
const exchanging = ref(false)
const verifying = ref(false)
const cardsLoading = ref(false)
const myCards = ref([])
const exchangedCards = ref([])
const cardTab = ref('issued')

const exchangeFormRef = ref()
const exchangeForm = reactive({
  cardNumber: '',
  cardPassword: ''
})

const exchangeRules = {
  cardNumber: [
    { required: true, message: '请输入卡号', trigger: 'blur' },
    { len: 16, message: '卡号必须是16位', trigger: 'blur' }
  ],
  cardPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { len: 16, message: '密码必须是16位', trigger: 'blur' }
  ]
}

// 金额格式化
const formatBalance = (balance) => {
  if (balance == null) return '0.00'
  const num = typeof balance === 'number' ? balance : parseFloat(balance)
  if (Number.isNaN(num)) return '0.00'
  return num.toFixed(2)
}

// 兑换额度卡
const handleExchange = async () => {
  try {
    await exchangeFormRef.value.validate()
    
    exchanging.value = true
    const response = await exchangeCard({
      cardNumber: exchangeForm.cardNumber.toUpperCase(),
      cardPassword: exchangeForm.cardPassword.toUpperCase()
    })
    
    if (response.success) {
      const amt = response.data?.amount
      const amountNum = typeof amt === 'number' ? amt : parseFloat(amt)
      ElMessage.success(`兑换成功！到账¥${Number.isNaN(amountNum) ? '-' : amountNum.toFixed(2)}`)
      // 清空表单
      exchangeForm.cardNumber = ''
      exchangeForm.cardPassword = ''
      // 刷新额度卡列表
      await fetchMyCards(cardTab.value === 'issued' ? 1 : 2)
      // 刷新用户信息以更新余额（Header 也会联动刷新）
      await userStore.refreshUserInfo()
    } else {
      ElMessage.error(response.message || '兑换失败')
    }
  } catch (error) {
    console.error('兑换失败:', error)
  } finally {
    exchanging.value = false
  }
}

// 验证卡密
const handleVerify = async () => {
  if (!exchangeForm.cardNumber || !exchangeForm.cardPassword) {
    ElMessage.warning('请先输入卡号和密码')
    return
  }
  
  verifying.value = true
  try {
    const response = await verifyCard({
      cardNumber: exchangeForm.cardNumber.toUpperCase(),
      cardPassword: exchangeForm.cardPassword.toUpperCase()
    })
    
    if (response.success) {
      ElMessage.success('验证成功！该额度卡可用')
    } else {
      ElMessage.error(response.message || '验证失败')
    }
  } catch (error) {
    console.error('验证失败:', error)
  } finally {
    verifying.value = false
  }
}

// 获取我的额度卡
const fetchMyCards = async (status) => {
  cardsLoading.value = true
  try {
    const response = await getMyCards(status ? { status } : {})
    
    if (response.success) {
      const cards = response.data || []
      if (status === 1) {
        myCards.value = cards
      } else if (status === 2) {
        exchangedCards.value = cards
      }
    }
  } catch (error) {
    console.error('获取我的额度卡失败:', error)
  } finally {
    cardsLoading.value = false
  }
}

// Tab切换
const handleCardTabChange = (tab) => {
  if (tab === 'issued') {
    fetchMyCards(1)
  } else if (tab === 'exchanged') {
    fetchMyCards(2)
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  fetchMyCards(1)
})
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.exchange-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.main-content {
  padding: 30px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 统计卡片区域 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px 28px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  overflow: hidden;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    transition: all 0.3s ease;
  }
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }
}

.stat-card-primary {
  &::before {
    background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  }
}

.stat-card-success {
  &::before {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  }
}

.stat-card-warning {
  &::before {
    background: linear-gradient(135deg, #E6A23C 0%, #EEB04F 100%);
  }
}

.stat-icon {
  width: 56px;
  height: 56px;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.1) 0%, rgba(102, 177, 255, 0.15) 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  margin-right: 16px;
  flex-shrink: 0;
}

.stat-card-success .stat-icon {
  background: linear-gradient(135deg, rgba(103, 194, 58, 0.1) 0%, rgba(133, 206, 97, 0.15) 100%);
}

.stat-card-warning .stat-icon {
  background: linear-gradient(135deg, rgba(230, 162, 60, 0.1) 0%, rgba(238, 176, 79, 0.15) 100%);
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 6px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

/* 页面标题 */
.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-title {
  font-size: 32px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}

.page-title-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  border-radius: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 16px;
  color: white;
  font-size: 28px;
}

.page-description {
  color: #606266;
  font-size: 16px;
}

/* 卡片样式 */
.exchange-card, .cards-list-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  margin-bottom: 30px;
  overflow: hidden;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }
}

.exchange-card .card-header {
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  padding: 28px 32px;
  color: white;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 4px;
    background: rgba(255, 255, 255, 0.3);
  }
}

.cards-list-card .card-header {
  background: linear-gradient(135deg, #9c27b0 0%, #ab47bc 100%);
  padding: 28px 32px;
  color: white;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 4px;
    background: rgba(255, 255, 255, 0.3);
  }
}

.card-title {
  font-size: 22px;
  font-weight: 600;
  display: flex;
  align-items: center;
  margin: 0;
}

.card-icon {
  margin-right: 12px;
  font-size: 28px;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.card-content {
  padding: 32px;
}

.form-item-compact {
  margin-bottom: 0;
}

.action-buttons {
  margin-top: 24px;
  margin-bottom: 0;
}

/* 按钮样式 */
.exchange-btn {
  background: linear-gradient(135deg, #67c23a 0%, #8dd64c 100%);
  border: none;
  border-radius: 10px;
  padding: 14px 36px;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  
  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 24px rgba(103, 194, 58, 0.45);
  }
  
  &:active {
    transform: translateY(-1px);
  }
}

.verify-btn {
  background: white;
  border: 2px solid #409EFF;
  color: #409EFF;
  border-radius: 10px;
  padding: 14px 36px;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  margin-left: 16px;
  
  &:hover {
    background: #409EFF;
    color: white;
    transform: translateY(-3px);
    box-shadow: 0 8px 24px rgba(64, 158, 255, 0.3);
  }
  
  &:active {
    transform: translateY(-1px);
  }
}

.btn-icon {
  font-size: 16px;
}

.amount-text {
  color: #67c23a;
  font-weight: 600;
}

/* 表单样式优化 */
:deep(.el-form) {
  .el-row {
    margin-bottom: 0;
  }
  
  .el-form-item {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .el-form-item__label {
    color: #606266;
    font-weight: 600;
    font-size: 15px;
    margin-bottom: 8px;
  }
}

:deep(.el-input__wrapper) {
  border-radius: 10px;
  padding: 8px 15px;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  
  &:hover {
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
  }
  
  &.is-focus {
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
}

:deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
  
  .el-table__header {
    th {
      background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      color: #606266;
      font-weight: 600;
      font-size: 14px;
      border-bottom: 2px solid #e4e7ed;
    }
  }
  
  .el-table__row {
    transition: all 0.3s ease;
    
    &:hover {
      background-color: #f8f9fa;
      transform: scale(1.01);
    }
  }
}

:deep(.el-tabs__header) {
  margin-bottom: 24px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  padding: 0 24px;
}

:deep(.el-tabs__active-bar) {
  height: 3px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .stats-section {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .main-content {
    padding: 20px 15px;
  }
  
  .stats-section {
    grid-template-columns: 1fr;
    gap: 16px;
    margin-bottom: 20px;
  }
  
  .stat-card {
    padding: 20px;
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
    font-size: 24px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .page-title {
    font-size: 24px;
    
    .page-title-icon {
      width: 40px;
      height: 40px;
      font-size: 22px;
    }
  }
  
  .page-description {
    font-size: 14px;
  }
  
  .card-header {
    padding: 20px 24px;
  }
  
  .card-content {
    padding: 20px 16px;
  }
  
  .exchange-btn, .verify-btn {
    width: 100%;
    justify-content: center;
    margin-left: 0;
  }
  
  .verify-btn {
    margin-top: 12px;
  }
  
  :deep(.el-col) {
    margin-bottom: 0;
  }
  
  .form-item-compact {
    margin-bottom: 20px;
  }
}
</style>

